package com.groupbuying.customer.service.impl;

import com.groupbuying.customer.connector.SysconfigFeign;
import com.groupbuying.customer.connector.WechatAliFeign;
import com.groupbuying.customer.constants.CommonConstants;
import com.groupbuying.customer.constants.CustomerPrizeEnumConstants;
import com.groupbuying.customer.constants.CustomerPrizeSearchConstants;
import com.groupbuying.customer.context.FilterContextHandler;
import com.groupbuying.customer.dao.CustomerInStorkDao;
import com.groupbuying.customer.dao.CustomerPrizeDao;
import com.groupbuying.customer.dao.CustomerUshopDao;
import com.groupbuying.customer.domain.*;
import com.groupbuying.customer.service.CustomerPrizeService;
import com.groupbuying.customer.service.CustomerUshopService;
import com.groupbuying.customer.service.CustomerWxinInfoService;
import com.groupbuying.customer.service.CustomerWxinfoRelService;
import com.groupbuying.customer.utils.JwtUtils;
import com.groupbuying.customer.utils.RedisUtils;
import com.groupbuying.customer.utils.apiresult.ApiResult;
import com.groupbuying.customer.utils.apiresult.ApiResultCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class CustomerPrizeServiceImpl implements CustomerPrizeService {
	private static final Logger logger = LoggerFactory.getLogger(CustomerPrizeServiceImpl.class);
	@Autowired
	private CustomerPrizeDao customerPrizeDao;
	@Autowired
	private CustomerWxinInfoService customerWxinInfoService;
	@Autowired
	private CustomerWxinfoRelService customerWxinfoRelService;
	@Autowired
	private CustomerUshopService customerUshopService;
	@Autowired
	CustomerInStorkDao customerInStorkDao;
	@Autowired
	private SysconfigFeign sysconfigFeign;
	@Autowired
	CustomerUshopDao customerUshopDao;
	@Autowired
	RedisUtils redisUtils;

	@Autowired
	private WechatAliFeign wechatAliFeign;
	@Override
	public CustomerPrizeDO get(String uuid){
		return customerPrizeDao.get(uuid);
	}
	
	@Override
	public List<CustomerPrizeDO> list(Map<String, Object> map){
		return customerPrizeDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return customerPrizeDao.count(map);
	}
	
	@Override
	public int save(CustomerPrizeDO customerPrize){
		return customerPrizeDao.save(customerPrize);
	}
	
	@Override
	public int update(CustomerPrizeDO customerPrize){
		return customerPrizeDao.update(customerPrize);
	}
	
	@Override
	public int remove(String uuid){
		return customerPrizeDao.remove(uuid);
	}
	
	@Override
	public int batchRemove(String[] uuids){
		return customerPrizeDao.batchRemove(uuids);
	}

	@Override
	public ApiResult wxRegistForPrize(Map<String, Object> param) {

		Object tempParam = param.get("wxCode");
		String wxCode = tempParam == null ? null : tempParam.toString();

		if (StringUtils.isEmpty(wxCode)) {
			return ApiResult.paramIsNull();
		}
		//查询openId
		Map<String,String> resMap = wechatAliFeign.getOpenidAndSessionKeyByCode(wxCode,"youdianproductor");
		if (resMap == null){
			return ApiResult.paramIsNull();
		}
		String openId = resMap.get("openid");
		if (openId == null){
			return ApiResult.paramIsNull();
		}
		Map<String,Object> map  = new HashMap<>();
		map.put(CustomerPrizeSearchConstants.SEARCH_OPENID,openId);


		List<CustomerWxinfoRelDO> resultList = customerWxinfoRelService.list(map);
		CustomerUshopDO customerUshopDO = null;
		if(resultList==null||resultList.size()==0){
			//创建子平台账户
			customerUshopDO = new CustomerUshopDO();
			customerUshopDO.setCustomerId(sysconfigFeign.getCustomerID());
			customerUshopDO.setGmtCreate(new Date());
			customerUshopDO.setGmtModified(new Date());
			customerUshopDO.setIsDelete(CommonConstants.COMMON_FLAG_UNDEL);
			customerUshopDO.setType(CommonConstants.MLS);
			customerUshopDO.setMainUuid("");
			customerUshopService.save(customerUshopDO);

			// 创建微信关系
			CustomerWxinfoRelDO customerWxinfoRelDO_new = new CustomerWxinfoRelDO();
			customerWxinfoRelDO_new.setCustomerId(customerUshopDO.getCustomerId());
			customerWxinfoRelDO_new.setIsDelete(CommonConstants.COMMON_FLAG_UNDEL);
			customerWxinfoRelDO_new.setGmtCreate(new Date());
			customerWxinfoRelDO_new.setGmtModified(new Date());
			customerWxinfoRelDO_new.setOpenId(openId);
			customerWxinfoRelService.save(customerWxinfoRelDO_new);
		}else{
			logger.info("用户已存在");
			CustomerWxinfoRelDO customerWxinfoRelDO = resultList.get(0);
			customerUshopDO = customerUshopService.get(customerWxinfoRelDO.getCustomerId());
		}
		try {

			Map<String,String> paramMap = new HashMap<>();
			UserToken userToken = new UserToken(customerUshopDO.getMobile(), customerUshopDO.getCustomerId(), "");
			String token = JwtUtils.generateToken(userToken, CommonConstants.COMMON_TOKEN_DAY * 24 * 60 * 60 * 1000);
			paramMap.put("token", token);
			return ApiResult.success(ApiResultCode.SUCCESS_LOGIN, paramMap);
		}catch (Exception e){
		e.printStackTrace();
		}
		return  ApiResult.failure("获取access_token失败");
	}
	@Transactional
	@Override
	public ApiResult savaPrizeMessage(Map<String, String> param) {


		//1是摇号2是转盘
		Object tempType = param.get("type");
		String type = tempType == null ? null : tempType.toString();
		Object tempPrize = param.get("prize");
		String prize = tempPrize == null ? null : tempPrize.toString();
		Object tempMobile = param.get("mobile");
		String mobile = tempMobile == null ? null : tempMobile.toString();
		//娃娃机-doll-1,垃圾分类-rubbish-2,模拟超市-market-3
		Object tempSource = param.get("source");
		//奖品标识
		Object tempidentifi = param.get("identifi");
		String identifi=tempidentifi==null?null:tempidentifi.toString();
		String source = tempSource == null ? null : tempSource.toString();

		String customerId = FilterContextHandler.getUserID();

		if(type.equals("2")){
			boolean hasKey = redisUtils.isHasKey("customer76123" + customerId);
			if(hasKey){
				return ApiResult.failure("正在抽奖中");
			}else {
				redisUtils.setKey("customer76123" + customerId,customerId,20*60);
			}
		}
		CustomerPrizeDO customerPrizeDO = new CustomerPrizeDO();
		//String customerId = sysconfigFeign.getCustomerID();
		Map<String, String> map = new HashMap<>();
		map.put("source", source);
		map.put("identifi", identifi);
		CustomerInStorkDO customerInStorkDO = customerInStorkDao.getNumberByName(map);
		int number = customerInStorkDO.getNumber() - 1;
		int save=0;
		if(number>=0){


			//logger.info("参与抽奖次数：{}",tempTime);
			customerPrizeDO.setCustomerId(customerId);
			customerPrizeDO.setPrize(prize);
			customerPrizeDO.setSource(source);
			customerPrizeDO.setIdentifi(identifi);
			//customerPrizeDO.setTimes(tempTime+1);
			customerPrizeDO.setDelflag(CustomerPrizeEnumConstants.ENUM_ISDELETE_UNDEL);
			customerPrizeDO.setGmtTime(new Date());
			customerPrizeDO.setType(type);
			customerPrizeDO.setMobile(mobile);
			save = customerPrizeDao.save(customerPrizeDO);
		//根据中奖来源以及奖品减库存
			customerInStorkDO.setNumber(number);
			customerInStorkDao.update(customerInStorkDO);
		}
		return ApiResult.success(save);

	}

	@Override
	public List<CustomerPrizeDO> getPrizeDetails(String source) {
		return customerPrizeDao.getPrizeDetails(source);

	}

	@Override
	public ApiResult getMessageBytype(String type) {
		//获取摇号中奖用户电话号码
		Set<String> mobileSet = customerPrizeDao.getMobile(CustomerPrizeEnumConstants.ENUM_TYPE_rock);
		logger.info("摇号中奖:{}",mobileSet.size());
		//获取马拉松用户用户电话号码
		Set<String> mobileByType = customerUshopDao.getMobileByType(type);
		logger.info("开始:{}",mobileByType.size());
		mobileByType.removeAll(mobileSet);
		logger.info("获取:{}",mobileByType.size());
		Random random = new Random();
		if(mobileByType.size()>0){
			logger.info("去重之后的Size：{}",mobileByType.size());
			int r = random.nextInt(mobileByType.size());
			logger.info("返回的参数为:{}",r);
			List<String> list = new ArrayList<>(mobileByType);
			String mobile = list.get(r);
			CustomerPrizeDO customerPrizeDO = new CustomerPrizeDO();
			customerPrizeDO.setType(type);
			customerPrizeDO.setMobile(mobile);
			customerPrizeDO.setDelflag(CustomerPrizeEnumConstants.ENUM_ISDELETE_UNDEL);
			customerPrizeDO.setGmtTime(new Date());
			int save = customerPrizeDao.save(customerPrizeDO);
			return ApiResult.success(mobile);

		}
		return ApiResult.failure("2");
	}

	@Override
	public Map<String, Object> sumPrize(Map<String, String> param) {
		String source = param.get("source");
		//String identifi = param.get("identifi");
		//查询各个奖品数量
		Integer detaile = customerPrizeDao.sumPrize(param);
		Map<String,String> map  = new HashMap<>();
		map.put("source",source);
		Integer all = customerPrizeDao.sumPrize(map);

		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put("detaile",detaile);
		paramMap.put("all",all);
		return paramMap;
	}

	@Override
	public Integer countCustomerForMls() {
		Map<String,Object> map = new HashMap<>();
		map.put("type",CommonConstants.MLS);
		return customerUshopDao.count(map);

	}

	@Override
	public Map<String, Integer> sumEvenPrize() {
		Map<String,String> mapDoll = new HashMap<>();
		mapDoll.put("source",CustomerPrizeEnumConstants.ENUM_SOURCE_DOLL);
		//娃娃机
		Integer doll = customerPrizeDao.sumEvenPrize(mapDoll);
		Map<String,String> mapRubbish = new HashMap<>();
		mapRubbish.put("source",CustomerPrizeEnumConstants.ENUM_SOURCE_RUBBISH);
		//垃圾分类
		Integer rubbish = customerPrizeDao.sumEvenPrize(mapRubbish);
		Map<String,String> mapMarket = new HashMap<>();
		mapMarket.put("source",CustomerPrizeEnumConstants.ENUM_SOURCE_MARKET);
		//模拟超市
		Integer market = customerPrizeDao.sumEvenPrize(mapMarket);


		Map<String,String> mapRock = new HashMap<>();
		mapRock.put("type",CustomerPrizeEnumConstants.ENUM_TYPE_rock);
		//摇号
		Integer rock = customerPrizeDao.sumEvenPrize(mapRock);
		Map<String,Integer> result = new HashMap<>();
		result.put("doll",doll);
		result.put("rubbish",rubbish);
		result.put("market",market);
		result.put("rock",rock);
		return result;
	}

	@Override
	public List<CustomerPrizeDO> getPrizeFormSource(String source) {
		return customerPrizeDao.getPrizeFormSource(source);
	}

	@Override
	public List<CustomerPrizeDO> getPrizeFormType(String type) {
		return customerPrizeDao.getPrizeFormType(type);
	}

	@Override
	public ApiResult saveScreen(Map<String, String> map) {
		String type = map.get("type");
		String mobile = map.get("mobile");
		CustomerPrizeDO customerPrizeDO = new CustomerPrizeDO();
		customerPrizeDO.setType(type);
		customerPrizeDO.setMobile(mobile);
		customerPrizeDO.setDelflag(CustomerPrizeEnumConstants.ENUM_ISDELETE_UNDEL);
		customerPrizeDO.setGmtTime(new Date());
		int save = customerPrizeDao.save(customerPrizeDO);
		return ApiResult.success(save);
	}

	@Override
	public ApiResult getTimeBySourceAndCustomerId(Map<String, String> map) {
		Integer times = customerPrizeDao.getTimeBySourceAndMobile(map);
		if(times>=1){
			return ApiResult.failure("对不起，每人只允许1次抽奖哦!");
		}
		return ApiResult.success();
	}

}
